<template>
  <el-dialog
    v-if="load"
    :title="title"
    v-model="visible"
    align-center
    width="600px"
    @close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      label-align="right"
      label-width="110"
      label-position="top"
    >
      <el-row :gutter="20">
        <el-col :span="21">
          <el-form-item label="主SKU" prop="name">
            <el-input v-model="custom_sku" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3" class="mt-7">
          <el-form-item label="" label-width="0" prop="status">
            <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              inline-prompt
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="辅料SKU" prop="supplier_name">
            <el-input v-model.trim="form.accessory_sku" placeholder="请选择" readonly>
              <template #append>
                <el-button
                  style="background-color: #3487ff; color: #ffffff"
                  type="primary"
                  @click="checkedSKU()"
                  :loadings="loadings.sku"
                  >选择辅料</el-button
                >
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="辅料名称" prop="supplier_name">
            <div>{{ form.accessory_name }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.accessories_use == 1 && types == 'add'">
          <el-form-item label="加工说明">
            <el-select
              class="w-full"
              v-model="form.processing_method"
              placeholder="加工说明"
              @change="changeProcessingMethod($event)"
            >
              <el-option
                v-for="item in (
                  options['goods.GoodsSkuIdentificationProcessing']?.[0]
                    ?.processingMethodText || []
                ).filter((i) => i.label !== '无需加工')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          v-if="
            form.accessories_use == 1 && types == 'add' && form.processing_method == 1
          "
        >
          <el-form-item label="&nbsp;">
            <el-checkbox
              v-model="form.is_refund_warehouse"
              label="是否回仓"
              size="large"
              :true-value="1"
              :false-value="0"
            />
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="is_refund_warehouse_tooltip"
              placement="top-start"
            >
              <svg-icon icon-class="QuestionFilled"></svg-icon>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <div class="flex">
          <el-col :span="10">
            <el-form-item label="数量" prop="supplier_name">
              <el-input-number
                v-model="form.quantity_main"
                :min="0"
                :max="999"
                controls-position="right"
                placeholder="主SKU"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-form-item prop="supplier_name">
              <template #label> &nbsp; </template>
              <span>:</span>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="" prop="supplier_name">
              <template #label> &nbsp; </template>
              <el-input-number
                v-model="form.quantity_auxiliary"
                :min="0"
                :max="999"
                controls-position="right"
                placeholder="辅料SKU"
              />
            </el-form-item>
          </el-col>
        </div>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              v-model.trim="form.remark"
              :autosize="{ minRows: 4, maxRows: 10 }"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">保 存</el-button>
    </template>
  </el-dialog>
  <checkedList ref="checkedListRef" @checked="checkedItem"></checkedList>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { reactive } from "vue";
import checkedList from "./list.vue";
import { is_refund_warehouse_tooltip } from "@/utils/tooltip.js";

let options = reactive(inject("options"));

const load = ref(false);
const visible = ref(false);
let loadings = reactive({});

const emit = defineEmits(["close", "updateForm"]);

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
  listData: {
    type: Array,
    default: () => {
      return [];
    },
  },
  custom_sku: {
    type: String,
    default: () => {
      return "";
    },
  },
  item: {
    type: Object,
    default: () => {
      return {};
    },
  },
  supplierData: {
    type: Array,
    default: () => [],
  },
});

const { item, supplierData } = toRefs(props);

const custom_sku = computed({
  get: () => props.custom_sku,
});

const statusMap = new Map([
  ["add", "新增关联辅料"],
  ["edit", "编辑关联辅料"],
]);

const title = ref("");
const types = ref("");
// 打开弹窗
const open = async (type, row) => {
  title.value = statusMap.get(type);
  types.value = type;
  initForm();
  if (!load.value) {
    load.value = true;
    await 1;
  }
  loadings = reactive({
    sku: false,
  });
  if (row) form.value = Object.assign({}, row);
  visible.value = true;
};

let form = ref({
  sku: "",
  custom_sku: "",
  accessory_sku: "",
  custom_accessory_sku: "",
  accessory_name: "",
  unit_cost_rmb: "",
  quantity_main: null,
  quantity_auxiliary: null,
  status: 1,
  remark: "",
});

const initForm = () => {
  form.value = getForm();
};
// 初始化
const getForm = () => {
  return {
    sku: "",
    custom_sku: "",
    accessory_sku: "",
    custom_accessory_sku: "",
    accessory_name: "",
    unit_cost_rmb: "",
    quantity_main: null,
    quantity_auxiliary: null,
    status: 1,
    remark: "",
  };
};
// 关闭弹窗
const close = () => {
  visible.value = false;
};

const checkedListRef = ref();
const checkedSKU = () => {
  checkedListRef.value.open();
};

const checkedItem = (item) => {
  form.value.accessory_sku_id = item.id;
  form.value.accessories_goods_sku = {
    sku_cn_title: item.sku_cn_title,
    custom_sku: item.custom_sku,
    sku: item.sku,
    sku_cn_title: item.sku_cn_title,
  };
  form.value.accessory_sku = item.sku || item.custom_sku;
  form.value.default_supplier = item.default_supplier;
  form.value.accessories_use = item.accessories_use;
  form.value.processing_method = "";
  form.value.accessory_name = item.sku_cn_title;
};
const handleClose = () => {
  initForm();
  emit("close");
};
// 提交
const save = () => {
  if (!form.value.accessory_sku) {
    ElMessage.error("请输入辅料SKU");
    return;
  }
  if (!form.value.quantity_main || !form.value.quantity_auxiliary) {
    ElMessage.error("请输入数量");
    return;
  }
  const findIndex = props.listData.findIndex(
    (i) => !i.delete && i.accessories_goods_sku?.sku == form.value.accessory_sku
  );

  if (findIndex != -1 && types.value == "add") {
    ElMessage.error("当前选择辅料SKU，不能重复选择");
    return;
  }
  if (supplierData?.length) {
    if (form.value.accessories_use == 1 && !form.value.processing_method) {
      return ElMessage.error("请选择加工说明");
    }
  }
  emit("updateForm", form.value);
  close();
};

defineExpose({ open });

const changeProcessingMethod = () => {
  form.value.is_refund_warehouse = "";
};
</script>
